package cn.yunhe.dao.impl;

import cn.yunhe.dao.AccountDao;
import cn.yunhe.pojo.Account;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import java.sql.SQLException;
import java.util.List;

public class AccountDaoImpl extends HibernateDaoSupport implements AccountDao {

    @Override
    public boolean insertAccount(Account account) {
        getHibernateTemplate().save(account);
        return false;
    }

    @Override
    public boolean updateAccount(Account account) {
        getHibernateTemplate().update(account);
        return false;
    }

    @Override
    public boolean deleteAccount(int id) {
        getHibernateTemplate().delete(this.getById(id));
        return false;
    }

    @Override
    public Account getById(int id) {
        return getHibernateTemplate().get(Account.class,id);
    }

    @Override
    public List<Account> findAccount(String hql) {
        List<Account>accountList=getHibernateTemplate().find(hql);
        return accountList;
    }

    @Override
    public List<Account> findAccount(final Account account) {
        List<Account>accountList=getHibernateTemplate().executeFind(new HibernateCallback<List<Account>>() {
            @Override
            public List<Account> doInHibernate(Session session) throws HibernateException, SQLException {
                Criteria criteria=session.createCriteria(Account.class);
                if (account!=null){
                    if (account.getId()>0){
                        criteria.add(Restrictions.eq("id",account.getId()));
                    }
                    if (account.getAname()!=null&&!account.getAname().equals("")){
                        criteria.add(Restrictions.like("aname",account.getAname(),MatchMode.ANYWHERE));
                    }
                    if (account.getAdate()!=null&&!account.getAdate().equals("")){
                        criteria.add(Restrictions.like("adate",account.getAdate(),MatchMode.ANYWHERE));
                    }
                    //Double引用数据类型
                    if (account.getAmoney()!=null&&account.getAmoney()>0){
                        criteria.add(Restrictions.gt("amoney",account.getAmoney()));
                    }
                }
                List<Account>accountList111=criteria.list();
                return accountList111;
            }
        });
        return accountList;
    }
}
